import socket
import threading

bind_id = '0.0.0.0'
bind_port = 9999

# 创建， 绑定， 监听
# 相当于一个公司
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_id, bind_port))
server.listen(5)

print("[*] Listening on %s:%d" % (bind_id, bind_port))


# 接受并发送
def handle_client(client_socket):
    while True:
        request = ""
        while True:
            tmp = client_socket.recv(1024)
            print(tmp)
            request += str(tmp)
            if len(tmp) < 1024:
                break

        print("[*] Received: %s" % request)

        client_socket.send(b"ACK!")

        if request == 'close':
            client_socket.close()
            break

cnt = 0

while True:
    # 接听
    # 相当于一个前台，接待人员
    print('times' + str(cnt))
    client, addr = server.accept()

    print(client)
    print(addr)
    print("[*] Accepted connection from:%s:%d" % (addr[0], addr[1]))

    client_handler = threading.Thread(target=handle_client, args=(client, ))
    client_handler.start()

    cnt += 1
